package com.earthchen.core.support.aop;

import com.alibaba.fastjson.JSONObject;
import com.earthchen.core.constants.BusinessStatus;
import com.earthchen.core.support.log.domain.OperationLog;
import com.earthchen.core.support.log.AsyncFactory;
import com.earthchen.core.support.log.LogManager;
import com.earthchen.core.support.log.annotation.BussinessLog;
import com.earthchen.core.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * 日志切面
 *
 * @author earthchen
 * @date 2018/8/24
 **/
@Aspect
@Component
@EnableAsync
public class LogAop {

    private Logger log = LoggerFactory.getLogger(this.getClass());


    @Pointcut(value = "@annotation(com.earthchen.core.support.log.annotation.BussinessLog)")
    public void logPointCut() {
    }

    /**
     * 前置通知 用于拦截操作
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }

    @Async
    protected void handleLog(final JoinPoint joinPoint, final Exception e) {
        try {
            // 获得注解
            BussinessLog controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }

            // 获取当前的用户
//            User currentUser = ShiroUtils.getUser();

            // *========数据库日志=========*//
            OperationLog operLog = new OperationLog();
            operLog.setStatus(BusinessStatus.SUCCESS);
            operLog.setMessage("操作成功");

            operLog.setCreatetime(new Date());
            // 请求的地址

            operLog.setOperUrl(WebUtil.getRequest().getRequestURI());


            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL);
                operLog.setMessage(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 处理设置注解上的参数
            getControllerMethodDescription(controllerLog, operLog);
            // 保存数据库
            LogManager.me().executeLog(AsyncFactory.bussinessLog(operLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log
     * @param operLog
     * @throws Exception
     */
    public void getControllerMethodDescription(BussinessLog log, OperationLog operLog) throws Exception {
        // 设置日志类型
        operLog.setLogtype(log.type());
        // 设置日志名字
        operLog.setLogname(log.value());
        // 获取参数的信息，传入到数据库中。
        setRequestValue(operLog);
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operLog
     */
    private void setRequestValue(OperationLog operLog) {
        Map<String, String[]> map = WebUtil.getRequest().getParameterMap();
        String params = JSONObject.toJSONString(map);
        operLog.setOperParams(params);
    }


    /**
     * 是否存在注解，如果存在就获取
     *
     * @param joinPoint
     * @return
     * @throws Exception
     */
    private BussinessLog getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(BussinessLog.class);
        }
        return null;
    }


}
